import React, { useState, useCallback, useEffect } from 'react';
import {
  ScrollView,
  TouchableOpacity,
  Text,
  View,
  StyleSheet,
} from 'react-native';
import { Table, Row, Rows } from 'react-native-table-component';
import { Button, Modal, Flex, Toast, List } from '@ant-design/react-native';
import { IconX } from '@/rcomponents/iconx';
import RadioButtonGroup from '@/rcomponents/radioButtonGroup';
import ShipRequesterScan from './components/shipRequesterScan';
import RnBarcodeScanner from './components/rnBarcodeScanner';
import InstructShipStore from './instructShipStore';
import ShipResultPage from './shipResultPage';

const styles = StyleSheet.create({
  filterBtnFlex: {
    justifyContent: 'flex-end',
    paddingRight: 10,
  },
  listHeader: { marginBottom: 5 },
  tableBorder: {
    borderColor: '#ddd',
    borderWidth: 1,
    borderBottomWidth: 0,
  },
  tableHeadSty: {
    borderBottomWidth: 2,
    borderColor: '#ddd',
  },
  tableRowSty: {
    height: 30,
    borderBottomWidth: 1,
    borderColor: '#ddd',
  },
});

function InstructShipDetailPage({ navigation, route }) {
  const insStore = InstructShipStore.useStore();
  const [filterOpt, setFilterOpt] = useState('all');
  const [scanVisible, setScanVisible] = useState(false);
  const [lockTable, setLockTable] = useState({
    visible: false,
    lockAvails: {
      locks: [],
      avails: [],
    },
  });
  useEffect(() => {
    navigation.setOptions({
      title: route.params.instructTitle,
    });
    insStore.getShipDetails(route.params.instructId);
  }, [route.params]);
  const detailTableHead = ['件号', '数量', '架位'];
  const detailTableRowFlex = [5, 2, 3];
  const lockTableHead = [
    '件号(序号)',
    '系统批次号',
    '架位',
    '到期日期',
    '数量',
  ];
  const lockTableRowFlex = [3, 3, 2, 3, 2];
  return (
    <>
      <Flex style={styles.listHeader}>
        {route.params.showRequester && (
          <Flex.Item>
            <ShipRequesterScan />
          </Flex.Item>
        )}
        <Flex.Item>
          <Flex style={styles.filterBtnFlex}>
            <RadioButtonGroup
              value={filterOpt}
              options={[
                { value: 'all', text: '全部' },
                { value: 'selected', text: '待取' },
              ]}
              onChange={(val) => setFilterOpt(val)}
            />
          </Flex>
        </Flex.Item>
      </Flex>
      <ScrollView>
        <Table borderStyle={styles.tableBorder}>
          <Row
            data={detailTableHead}
            style={styles.tableHeadSty}
            textStyle={styles.text}
            flexArr={detailTableRowFlex}
          />
          {insStore.instructDetails.map((insd) => (
            <TouchableOpacity
              onPress={() =>
                setLockTable({
                  visible: true,
                  lockAvails: insd.children,
                })
              }
              key={insd.id}
            >
              <Row
                data={[insd.pn, insd.count, insd.rackno]}
                flexArr={detailTableRowFlex}
                textStyle={styles.tableRowSty}
              />
            </TouchableOpacity>
          ))}
        </Table>
      </ScrollView>
      <List>
        <List.Item
          extra={<IconX name="scan" origin="ionicons" />}
          onPress={() => setScanVisible(true)}
        >
          预准备清单
          <List.Item.Brief>架位：13-A-01 箱号：20010001</List.Item.Brief>
        </List.Item>
      </List>
      <Modal
        visible={scanVisible}
        onClose={() => {
          setScanVisible(false);
        }}
      >
        <RnBarcodeScanner
          scanProcessing={insStore.getShipBoxDetails.loading}
          onBarCodeRead={async (barcode) => {
            const boxRes = await insStore.getShipBoxDetails(barcode);
            setScanVisible(false);
            if (boxRes.errorCode) {
              Toast.fail('条码获取箱号发料信息失败, 请重试');
            } else {
              /* 根据box detail结果更新instructStore 领取数量 */
            }
          }}
          onExitScan={() => {
            setScanVisible(false);
          }}
        />
      </Modal>
      <Modal
        popup
        visible={lockTable.visible}
        animationType="slide-up"
        onClose={() =>
          setLockTable({
            visible: false,
            lockAvails: { locks: [], avails: [] },
          })
        }
        maskClosable
      >
        <List renderHeader={<Text>锁定列表</Text>}>
          <List.Item>
            <Table borderStyle={styles.tableBorder}>
              <Row
                data={lockTableHead}
                style={styles.head}
                textStyle={styles.text}
                flexArr={lockTableRowFlex}
              />
              <Rows
                data={lockTable.lockAvails.locks.map((lk) => [
                  lk.pn + lk.sn,
                  lk.batch_no,
                  lk.rackno,
                  lk.date,
                  lk.count,
                ])}
                style={styles.head}
                textStyle={styles.text}
                flexArr={lockTableRowFlex}
              />
            </Table>
          </List.Item>
        </List>
        <List renderHeader={<Text>可选类别</Text>}>
          <List.Item>
            <Table borderStyle={styles.tableBorder}>
              <Row
                data={lockTableHead}
                style={styles.head}
                textStyle={styles.text}
                flexArr={lockTableRowFlex}
              />
              <Rows
                data={lockTable.lockAvails.avails.map((lk) => [
                  lk.pn + lk.sn,
                  lk.batch_no,
                  lk.rackno,
                  lk.date,
                  lk.count,
                ])}
                style={styles.head}
                textStyle={styles.text}
                flexArr={lockTableRowFlex}
              />
            </Table>
          </List.Item>
        </List>
      </Modal>
      <Button
        type="primary"
        onPress={() => {
          /* 发料接口 */
          navigation.navigate(ShipResultPage.routeName, {
            from: 'Instruct',
          });
        }}
      >
        确定发料
      </Button>
    </>
  );
}

InstructShipDetailPage.routeName = 'InstructShipDetailPage';
InstructShipDetailPage.permission = 'RInstructShipDetail';
export default InstructShipDetailPage;
